﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "convertlist.h"
#include "addtaskwizard.h"
#include "language.h"
#include "optionsdialog.h"
#include "poweroffdialog.h"
#include "dialog.h"
#include "services/extensions.h"
#include "services/paths.h"
#include "services/notification.h"
#include "services/powermanagement.h"
#include "converter/mediaconverter.h"
#include "converter/presets.h"
#include <QIcon>
#include <QHBoxLayout>

MainWindow::MainWindow(QTranslator& translator, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::dealsofts)
    , m_translator(translator)
    , m_presets(new Presets(this))
    , m_list(new ConvertList(m_presets, this))
    , m_view(new QWebView)
    , m_homeURL("http://www.dealsofts.com/free.html")
{
    ui->setupUi(this);
    

    connect(ui->pushButton_home, SIGNAL(clicked())
        , this, SLOT(slotHomeClicked()));
    connect(ui->pushButton_add, SIGNAL(clicked())
        , this, SLOT(slotAddFilesToList()));

    connect(ui->pushButton_left, SIGNAL(clicked()), this, SLOT(slotLeftClicked()));
    connect(ui->pushButton_right, SIGNAL(clicked()), this, SLOT(slotRightClicked()));

    connect(m_view, SIGNAL( linkClicked( QUrl ) )
        , this, SLOT(slotLinkClicked( QUrl ) ) );

    m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    ui->stackedWidget->addWidget(m_view);
    ui->stackedWidget->addWidget(m_list);

    ui->stackedWidget->setCurrentIndex(0);

    ui->stackedWidget_2->setCurrentIndex(0);

    m_view->load(QUrl(m_homeURL));   

    initData();

    if (!check_execute_conditions()) {
        // Close the window immediately after it has started.
        QTimer::singleShot(0, this, SLOT(close()));
    } else {
        QTimer::singleShot(0, this, SLOT(window_ready()));
    }

    // open file dialog default path
    QSettings settings;
    m_prev_path = settings.value("addtaskwizard/openfilepath" , QDir::homePath()).toString();
	QSettings *configIniRead = new QSettings(QCoreApplication::applicationDirPath() + "/conf.dll", QSettings::IniFormat);
    configIniRead->setIniCodec("UTF8");

    // 配置那些转码图标可以看到
    unsigned int logoCount = 8;  // 一页可以显示8个图标
    char* firstConvertItem[8] = {"apple","android","mp4","avi","mkv","flv", "wmv", "mpeg"};
    QPushButton* firstButtonItem[8] = {ui->pushButton_3_apple, ui->pushButton_2_android, ui->pushButton_8_mp4,\
        ui->pushButton_4_avi, ui->pushButton_7_mkv, ui->pushButton_1_flv, ui->pushButton_5_wmv, ui->pushButton_6_mpeg};
    for(int i = 0; i < 8; i++)
    {
        if(!configIniRead->value(QString("/convert/") + QString(firstConvertItem[i])).toInt())
        {
            logoCount--;
            ui->horizontalLayout->removeWidget(firstButtonItem[i]);
            firstButtonItem[i]->hide();
        }
    }

    // 下一页编码图标
    char* secondConvertItem[7] = {"ts","f4v","mov","3gp","asf","html5", "audio"};
    QPushButton* secondButtonItem[7] = {ui->pushButton_10_ts, ui->pushButton_11_f4v, ui->pushButton_12_mov,\
        ui->pushButton_13_3gp, ui->pushButton_14_asf, ui->pushButton_9_html5, ui->pushButton_15_audio};
    for(int i = 0; i < 7; i++)
    {
        if(!configIniRead->value(QString("/convert/") + QString(secondConvertItem[i])).toInt())
        {
            ui->horizontalLayout_2->removeWidget(secondButtonItem[i]);
            secondButtonItem[i]->hide();
        }
        else
        {
            if(logoCount++ < 8)
            {
                ui->horizontalLayout->addWidget(secondButtonItem[i]);
            }
        }
    }

    if(logoCount <= 8)
    {
        ui->pushButton_right->hide();
        ui->pushButton_left->hide();
    }

    // 设置默认语言
    m_selectLanaguageIndex = configIniRead->value(QString("/language/language")).toInt();
    LanguageDialog d(this->m_colorURL, m_selectLanaguageIndex, QString(), this);   
    QString paths = Paths::translationPath() + d.getTranslatorFileName(m_selectLanaguageIndex);
    m_translator.load(Paths::translationPath()  + d.getTranslatorFileName(m_selectLanaguageIndex));

    // 设置软件名字
    ui->label_software_name->setText(configIniRead->value(QString("/software/name")).toString());
        
    configIniRead->value(QString("/language/language")).toInt();

    // 翻译一下文字
    this->translateUi();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::deleteList()
{
	m_list->clear();
}

bool MainWindow::check_execute_conditions()
{
    QString errmsg;

    // check external programs
    if (!MediaConverter::checkExternalPrograms(errmsg)) {
        QMessageBox::critical(this, this->windowTitle(), errmsg);
        return false;
    }
    // load presets
    if (!load_presets())
        return false;

    return true;
}

void MainWindow::slotLeftClicked()
{
    ui->stackedWidget_2->setCurrentIndex(0);
    ui->pushButton_left->setEnabled(false);
    ui->pushButton_right->setEnabled(true);
}

void MainWindow::slotRightClicked()
{
    ui->stackedWidget_2->setCurrentIndex(1);
    ui->pushButton_left->setEnabled(true);
    ui->pushButton_right->setEnabled(false);
}

// Popup wizard to add tasks.
void MainWindow::add_files()
{
    AddTaskWizard wizard(m_presets, this);

    if (wizard.exec_openfile() == QDialog::Accepted) {
        // Add all input files to the list.
        const QList<ConversionParameters> &paramList = wizard.getConversionParameters();
        m_list->addTasks(paramList);
    }
}

void MainWindow::slotStartConversion()
{
}

void MainWindow::slotLinkClicked(QUrl url)
{
    m_view->load(url);  
}


void MainWindow::refresh_action_states()
{
    int selected_file_count = m_list->selectedCount();

    // Hide actionSetParameters if no item in m_list is selected.
    bool hide_SetParameters = (selected_file_count == 0);

    // Hide actionStartConversion if the conversion is in progress.
    bool hide_StartConversion = m_list->isBusy();

    // Hide actionStopConversion if nothing is being converted.
    bool hide_StopConversion = !m_list->isBusy();

    // Show actionOpenOutputFolder only if 1 file is selected.
    bool hide_OpenFolder = (selected_file_count <= 0);

    // Hide actionRemoveSelectedItems if no file is selected.
    bool hide_RemoveSelectedItems = (selected_file_count == 0);

    bool hide_Retry = (selected_file_count == 0);
    bool hide_RetryAll = (m_list->isEmpty());

    bool hide_ClearList = (m_list->isEmpty());

    bool hide_ChangeOutputFilename = m_list->selectedCount() != 1;
    bool hide_ChangeOutputDirectory = m_list->selectedCount() <= 0;


    /* Show actionShowErrorMessage if and only if one task is selected
       and the state of the selected task is FAILED
     */
    bool hide_ShowErrorMessage = (selected_file_count != 1
                                  || !m_list->selectedTaskFailed());
    /*
    ui->actionSetParameters->setDisabled(hide_SetParameters);
    ui->actionStartConversion->setDisabled(hide_StartConversion);
    ui->actionStopConversion->setDisabled(hide_StopConversion);
    ui->actionOpenOutputFolder->setDisabled(hide_OpenFolder);
    ui->actionRemoveSelectedItems->setDisabled(hide_RemoveSelectedItems);
    ui->actionRetry->setDisabled(hide_Retry);
    ui->actionRetryAll->setDisabled(hide_RetryAll);
    ui->actionClearList->setDisabled(hide_ClearList);
    ui->actionChangeOutputFilename->setDisabled(hide_ChangeOutputFilename);
    ui->actionChangeOutputDirectory->setDisabled(hide_ChangeOutputDirectory);
    ui->actionShowErrorMessage->setDisabled(hide_ShowErrorMessage);
    */
}

void MainWindow::slotHomeClicked()
{
    m_view->load(QUrl(m_homeURL));
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::slotAddFilesToList()
{
    ui->stackedWidget->setCurrentIndex(1);

    Extensions exts;
    m_params.clear();
    /*: This text is the title of an openfile dialog. */
    QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files"),
        m_prev_path,  // default path
        tr("All files") + " (*)" ";;" +
        tr("Multimedia") + exts.multimedia().forFilter() + ";;" +
        tr("Video") + exts.video().forFilter() + ";;" +
        tr("Audio") + exts.audio().forFilter()
        );

    if (!files.isEmpty()) {
        QStringList incorrect_files; // Record files that are not valid for conversion.

        foreach (QString file, files) {
            if (QFileInfo(file).isFile()) {       // The file exists.
                QListWidgetItem *item = new QListWidgetItem(file);
                item->setToolTip(file);
                
                {
                    QString input_file_basename = QFileInfo(file).completeBaseName();
                    //const QDir output_dir("D:\\www");
                    ConversionParameters param;
                    param.source = file;
                    param.destination = input_file_basename + ".?";//output_dir.absoluteFilePath(input_file_basename + ".flv");
                    m_params.append(param);
                }

                m_prev_path = QFileInfo(file).path(); // save file path
            } else if (QFileInfo(file).isDir()) { // The filename is a directory.
                incorrect_files.append(file);
            } else {                              // The file does not exist.
                incorrect_files.append(file);
            }
        }

        if (!incorrect_files.isEmpty()) {
            QMessageBox msgBox;
            msgBox.setText(tr("Some files could not be found."));
            msgBox.setDetailedText(incorrect_files.join("\n"));
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.setIcon(QMessageBox::Warning);
            msgBox.exec();
        }

        // Save open file path.
        QSettings settings;
        settings.setValue("addtaskwizard/openfilepath", m_prev_path);

    } else {
        // no file selected
        return;
    }

    if(!m_params.empty())
        m_list->addTasks(m_params);
}



bool MainWindow::load_presets()
{
    // The default preset file is located in <datapath>/presets.xml
    QString default_preset_file = QDir(Paths::dataPath()).absoluteFilePath("presets.xml");

#ifndef PORTABLE_APP
    // rename local preset file created by older versions of qwinff
    // operation: mv ~/.qwinff/presets.xml ~/.qwinff/presets.xml.old
    QString local_preset_file_old = QDir(QDir::homePath()).absoluteFilePath(".qwinff/presets.xml");
    if (QFile(local_preset_file_old).exists()) {
        QFile::remove(local_preset_file_old + ".old");
        if (QFile::rename(local_preset_file_old, local_preset_file_old + ".old")) {
            qDebug() << local_preset_file_old + " is no longer used, "
                "rename to " + local_preset_file_old + ".old";
        }
    }

    // use global preset temporarily
    QString local_preset_file = default_preset_file;
#else // PORTABLE_APP
    QString local_preset_file = default_preset_file;
#endif

    QSettings settings;
    bool removeUnavailableCodecs = settings.value("options/hideformats", true).toBool();
    // Load the preset file from the user's home directory
    // The presets are loaded once and shared between objects
    // that need the information.
    if (!m_presets->readFromFile(local_preset_file, removeUnavailableCodecs)) {
        QMessageBox::critical(this, this->windowTitle(),
            tr("Failed to load preset file. "
            "The application will quit now."));
        return false;
    }
    return true;
}

void MainWindow::paintEvent(QPaintEvent *)
{
	m_pixmapBg.load(this->m_colorURL);
    QPainter painter(this);
    painter.drawPixmap(m_pixmapBg.rect(), m_pixmapBg);
}

void MainWindow::translateUi()
{
    ui->retranslateUi(this);
}

void MainWindow::changeEvent(QEvent *event)
{
    if (event->type()==QEvent::LanguageChange)
    {
        this->translateUi();//更新界面
    }
    else
    {
        QMainWindow::changeEvent(event);
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    this->move(e->globalPos() - m_pointStart);
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    m_pointPress = e->globalPos();
    m_pointStart = m_pointPress - this->pos();

}

void MainWindow::setNomalStyle()
{  
    QFile styleSheet(":/res/qss/style_360.qss");
    if (!styleSheet.open(QIODevice::ReadOnly))
    {
        qWarning("Can't open the style sheet file.");
        return;
    }
    qApp->setStyleSheet(styleSheet.readAll());
}



void MainWindow::on_menuBtn_clicked()
{
    m_menu->exec(this->mapToGlobal(QPoint(760, 20)));
}

void MainWindow::initData()
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    m_menu = new QMenu();
    QMenu* m_colorMenu = m_menu->addMenu(tr("color"));
    QAction* languageAction = m_menu->addAction(tr("language"));
    connect(languageAction,SIGNAL(triggered()),this,SLOT(on_pushButton_language_clicked()));
    QAction* updateAction = m_menu->addAction(tr("update"));
    connect(updateAction,SIGNAL(triggered()),this,SLOT(updateSlot()));
    QAction* helpAction = m_menu->addAction(tr("help"));
    connect(helpAction,SIGNAL(triggered()),this,SLOT(helpSlot()));

	m_colorMap[tr("green")] = ":/res/image/background/green.jpg";
	m_colorMap[tr("vsunburst")] = ":/res/image/background/vsunburst.jpg";
	m_colorMap[tr("purple")] = ":/res/image/background/purple.jpg";
	m_colorMap[tr("pink")] = ":/res/image/background/pink.jpg";
	m_colorMap[tr("brown")] = ":/res/image/background/brown.jpg";
	m_colorMap[tr("blue")] = ":/res/image/background/blue.jpg";

	QMap<QString,QString>::Iterator it = m_colorMap.begin();
	while(it != m_colorMap.end())
	{
		QAction* action = new QAction(QIcon(it.value()), it.key() ,this);
		action->setData(it.key());
		m_colorMenu->addAction(action);
		++it;
	}

    QSettings *configIniRead = new QSettings(QCoreApplication::applicationDirPath() + "/conf.dll", QSettings::IniFormat);
    this->m_colorURL = m_colorMap[configIniRead->value("color/color").toString()];

	connect(m_colorMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorSlot(QAction*)));

    ///背景加载;
    m_vecBtn.push_back(ui->pushButton_1_flv);
    m_vecBtn.push_back(ui->pushButton_2_android);
    m_vecBtn.push_back(ui->pushButton_3_apple);
    m_vecBtn.push_back(ui->pushButton_4_avi);
    m_vecBtn.push_back(ui->pushButton_5_wmv);
    m_vecBtn.push_back(ui->pushButton_6_mpeg);
    m_vecBtn.push_back(ui->pushButton_7_mkv);
    m_vecBtn.push_back(ui->pushButton_8_mp4);
    m_vecBtn.push_back(ui->pushButton_9_html5);

    for (int i = 0; i != m_vecBtn.size(); ++i)
    {
        ///功能选择键只有一个被选中;
        m_vecBtn[i]->setCheckable(true);
        m_vecBtn[i]->setAutoExclusive(true);
    }

     setNomalStyle();
}

void MainWindow::updateSlot(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String("http://www.dealsofts.com/free_video_converter/update.html")));
}

void MainWindow::helpSlot(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String("http://www.dealsofts.com/free_video_converter/guide.html")));
}

void MainWindow::colorSlot(QAction* action)
{
	m_colorMap[action->data().toString()];
	this->m_colorURL = m_colorMap[action->data().toString()];
	update();
}

void MainWindow::StartConversion(QString category)
{
    if (m_list->isEmpty()) 
    {
        QMessageBox::information(this, this->windowTitle(),
            tr("Nothing to convert."), QMessageBox::Ok);
        return;
    }

	dialog d(m_colorURL, category, m_presets,this);
    d.show();

    QEventLoop loop(&d);
    connect(&d, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    if(d.getConvert())
    {
        m_list->setParm(d.m_current_param);
        m_list->start();
    }

    refresh_action_states();
}

void MainWindow::on_pushButton_1_flv_clicked()
{
    StartConversion("FLV");
    setCurrentWidget();
}

void MainWindow::on_pushButton_2_android_clicked()
{
    StartConversion("ANDROID");
    setCurrentWidget();
}

void MainWindow::on_pushButton_3_apple_clicked()
{
    StartConversion("APPLE");
    setCurrentWidget();
}

void MainWindow::on_pushButton_4_avi_clicked()
{
    StartConversion("AVI");
    setCurrentWidget();
}

void MainWindow::on_pushButton_5_wmv_clicked()
{
    StartConversion("WMV");
    setCurrentWidget();
}

void MainWindow::on_pushButton_6_mpeg_clicked()
{    
    StartConversion("MPEG");
    setCurrentWidget();
}

void MainWindow::on_pushButton_7_mkv_clicked()
{
    StartConversion("MKV");
    setCurrentWidget();
}

void MainWindow::on_pushButton_8_mp4_clicked()
{
    StartConversion("MP4");
     setCurrentWidget();
}

void MainWindow::on_pushButton_9_html5_clicked()
{
    StartConversion("HTML5");
    setCurrentWidget();
}

void MainWindow::on_pushButton_10_ts_clicked()
{
    StartConversion("TS");
    setCurrentWidget();
}

void MainWindow::on_pushButton_11_f4v_clicked()
{
    StartConversion("F4V");
    setCurrentWidget();
}

void MainWindow::on_pushButton_12_mov_clicked()
{
    StartConversion("MOV");
    setCurrentWidget();
}

void MainWindow::on_pushButton_13_3gp_clicked()
{
    StartConversion("3GP");
    setCurrentWidget();
}

void MainWindow::on_pushButton_14_asf_clicked()
{
    StartConversion("ASF");
    setCurrentWidget();
}

void MainWindow::on_pushButton_15_audio_clicked()
{
    StartConversion("AUDIO");
    setCurrentWidget();
}

void MainWindow::on_pushButton_language_clicked()
{
    QString translatorFile;
    LanguageDialog d(this->m_colorURL, m_selectLanaguageIndex, translatorFile, this);
    d.show();

    QEventLoop loop(&d);
    connect(&d, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    
    // 设置语言
    m_translator.load(Paths::translationPath()  + translatorFile);
}


void MainWindow::setCurrentWidget()
{
    /*
    for (int i = 0; i != m_vecBtn.size(); ++i)
    {
        if ( m_vecBtn[i]->isChecked() )
        {
            ui->stackedWidget->setCurrentIndex(i);
        }
    }
    */
}
